package com.max.sportmanage.config.security.service;

import com.max.sportmanage.entity.SysMenu;
import com.max.sportmanage.entity.SysRole;
import com.max.sportmanage.entity.SysUser;
import com.max.sportmanage.mapper.SysUserMapper;
import com.max.sportmanage.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @program: java-sport-manage
 * @description:实现userdetailservice
 * @author: max-qaq
 * @create: 2021-10-25 11:06
 **/
@Slf4j
@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    SysUserMapper sysUserMapper;

    @Autowired
    RedisUtil redisUtil;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.debug("获取用户信息");
        SysUser user;
        if (redisUtil.hasKey("userInfo_" + username)) {
            log.debug("缓存中存在用户信息，从缓存读取");
            user = (SysUser) redisUtil.getValue("userInfo_" + username);
            //刷新过期时间，只有不用的时候才会过期
            redisUtil.expire("userInfo_" + username,5);
        } else {
            user = sysUserMapper.findByUsername(username);
            if (null == user) {
                throw new UsernameNotFoundException("用户名或密码错误");
            }
            if (user.isAdmin()) {
                log.info("是管理员，进行操作");
                user.setRoles(sysUserMapper.findRoles(null));
                user.setPermissions(sysUserMapper.findPermissions(null));
                //查询父菜单
                List<SysMenu> parentMenus = sysUserMapper.findMenus(null);
                //设置子菜单
                parentMenus.forEach(item -> {
                    List<SysMenu> childMenus = sysUserMapper.findChildMenu(item.getId(), null);
                    item.setChildren(childMenus);
                });
                user.setMenus(parentMenus);
            } else {
                //非管理员要查询
                user.setRoles(sysUserMapper.findRoles(user.getId()));
                user.setPermissions(sysUserMapper.findPermissions(user.getId()));
                //查询父菜单
                List<SysMenu> parentMenus = sysUserMapper.findMenus(user.getId());
                //设置子菜单
                parentMenus.forEach(item -> {
                    List<SysMenu> childMenus = sysUserMapper.findChildMenu(item.getId(), user.getId());
                    item.setChildren(childMenus);
                });
                user.setMenus(parentMenus);
            }
            redisUtil.setValueTime("userInfo_" + username,user,5);
        }

        return user;

    }
}
